package com.jdqzyy.noobnoob.common.activeController;


import com.jdqzyy.noobnoob.common.annotation.ResponseResult;
import com.jdqzyy.noobnoob.common.resultVO.NoobResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.http.HTTPException;

/**
 * @author Zyy
 * @Description:重写返回体，统一的错误异常处理
 * @date 2020/11/21下午4:59
 * @slogan 天下风云出我辈，一入代码岁月催
 */
@RestControllerAdvice(basePackages = "com.jdqzyy.noobnoob")
@Slf4j
public class ResponseHandler implements ResponseBodyAdvice<Object> {
    /**
     * 标记名称
     */
    public static final String RESPONSE_RESULT_ANN = "RESPONSE-RESULT-ANN";

    /**
     * 是否请求 包含了 包装注解 标记，没有就直接返回，不需要重写返回体
     * @param methodParameter
     * @param aClass
     * @return
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        ServletRequestAttributes sra = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
        HttpServletRequest request = sra.getRequest();
        // 请求中是否包装标记
        ResponseResult responseResultAnn = (ResponseResult)request.getAttribute(RESPONSE_RESULT_ANN);
        return responseResultAnn != null;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        log.info("进入返回体 重写格式处理...");
        // 如果返回的内容就是NoobRest类型，那么就没必要再次封装
        if (body instanceof NoobResult) {
            return body;
        }
        return NoobResult.ok().data(body);
    }


}
